package com.supor.aiot.home.apdater;

import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.android.baseconfig.recyclerview.adapter.BaseByRecyclerViewAdapter;
import com.android.baseconfig.recyclerview.stickyview.StickyHeaderHandler;
import com.supor.aiot.common.adapter.BaseBindingHolder;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporApplication;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.utils.BitmapUtil;
import com.supor.aiot.home.R;
import com.supor.aiot.home.databinding.ItemNavigationBlankBinding;
import com.supor.aiot.home.databinding.ItemNavigationContentBinding;
import com.supor.aiot.home.databinding.ItemNavigationTitleBinding;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class NavigationContentAdapter extends BaseByRecyclerViewAdapter<ProductType.ProductModel,
        BaseBindingHolder> {

    private static final int TYPE_TITLE = 0x001;
    private static final int TYPE_CONTENT = 0x002;
    private static final int TYPE_BLANK = 0x003;
    // content部分对应分类的position
    private ArrayList<Integer> positions = new ArrayList<>();
    View blankView;
    Handler handler;
    int blankHeight;
    int currentPos = 0;

    public NavigationContentAdapter() {
        this.handler = new Handler(SuporApplication.getInstance().getMainLooper(),
                new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                ViewGroup.LayoutParams params = blankView.getLayoutParams();
                if (params.height > 0) {
                    params.height -= 10;
                } else {
                    return false;
                }
                blankView.setLayoutParams(params);
                handler.postDelayed(() -> handler.sendEmptyMessage(0), 1);
                return false;
            }
        });
        blankHeight = AppAgent.getApp().getResources().getDimensionPixelSize(R.dimen.dp_640);
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @NonNull
    @Override
    public BaseBindingHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == StickyHeaderHandler.TYPE_STICKY_VIEW) {
            return new ViewTitleHolder(parent, R.layout.item_navigation_title);
        } else if (viewType == TYPE_CONTENT) {
            return new ViewContentHolder(parent, R.layout.item_navigation_content);
        } else {
            return new ViewBlankHolder(parent, R.layout.item_navigation_blank);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if ("blank".equalsIgnoreCase(getData().get(position).productId)) {
            return TYPE_BLANK;
        } else if (TextUtils.isEmpty(getData().get(position).modelName)) {
            return StickyHeaderHandler.TYPE_STICKY_VIEW;
        } else {
            return TYPE_CONTENT;
        }
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof GridLayoutManager) {
            final GridLayoutManager gridManager = ((GridLayoutManager) manager);
            gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    int type = getItemViewType(position);
                    /**
                     * 根据GridLayoutManager的getSpanSize方法可以动态的设置item跨列数
                     * 需要设置：4个参数的GridLayoutManager
                     * new GridLayoutManager(getActivity(),6,GridLayoutManager.VERTICAL,false);
                     * 这里的6（自己设置的最好设置成偶数）就相当于分母，6默认显示一整行（1列），
                     * 下面的3 和2 就相当于分子，返回3就是（1/2）所以此类型对应的是2列，返回2就是（1/3）所以此类型对应的是3列
                     * */
                    switch (type) {
                        case StickyHeaderHandler.TYPE_STICKY_VIEW:
                            // title栏显示一列
                            return gridManager.getSpanCount();
                        case TYPE_CONTENT:
                            // 内容栏显示2列
                            return 3;
                        default:
                            //默认显示2列
                            return 3;
                    }
                }
            });
        }
    }

    public void setPositions(ArrayList<Integer> positions) {
        this.positions = positions;
        // Logc.e("setPositions: " + positions);
    }

    public void setBlankViewVisible(boolean visible) {
        if (blankView != null) {
            if (visible) {
                handler.removeCallbacksAndMessages(null);
                ViewGroup.LayoutParams params = blankView.getLayoutParams();
                params.height = blankHeight;
                blankView.setLayoutParams(params);
                blankView.setVisibility(View.VISIBLE);
            } else {
                handler.sendEmptyMessage(0);
            }
        }
    }

    public void notifyTitle(Integer integer) {
        if (getData() != null && getData().size() > 0) {
            getData().get(currentPos).selected = false;
            notifyItemChanged(currentPos);
            currentPos = integer;
            getData().get(currentPos).selected = true;
            notifyItemChanged(currentPos);
        }
    }

    private class ViewTitleHolder extends BaseBindingHolder<ProductType.ProductModel,
            ItemNavigationTitleBinding> {

        ViewTitleHolder(ViewGroup context, int layoutId) {
            super(context, layoutId);
        }

        @Override
        protected void onBindingView(BaseBindingHolder holder, ProductType.ProductModel dataBean,
                                     int position) {
            // Logc.e("onBindingView: " + position);
            if (dataBean != null) {
                binding.setBean(dataBean);
                if (TextUtils.isEmpty(dataBean.modelTypeName)) {
                    binding.idByStickyItem.setVisibility(View.INVISIBLE);
                } else {
                    binding.idByStickyItem.setVisibility(View.VISIBLE);
                }
                binding.tvTitle.setText(dataBean.modelTypeName);
                if (dataBean.selected) {
                    binding.tvTitle.setTypeface(Typeface.DEFAULT_BOLD);
                } else {
                    binding.tvTitle.setTypeface(Typeface.DEFAULT);
                }
                ViewGroup.MarginLayoutParams p =
                        (ViewGroup.MarginLayoutParams) binding.tvTitle.getLayoutParams();
                if (position == 0) {
                    p.setMargins(p.leftMargin,
                            holder.itemView.getResources().getDimensionPixelSize(R.dimen.dp_12),
                            p.rightMargin, p.bottomMargin);
                } else {
                    p.setMargins(p.leftMargin,
                            holder.itemView.getResources().getDimensionPixelSize(R.dimen.dp_20),
                            p.rightMargin, p.bottomMargin);

                }
                binding.tvTitle.setLayoutParams(p);
            }
        }
    }

    private class ViewContentHolder extends BaseBindingHolder<ProductType.ProductModel,
            ItemNavigationContentBinding> {

        ViewContentHolder(ViewGroup context, int layoutId) {
            super(context, layoutId);
        }

        @Override
        protected void onBindingView(BaseBindingHolder holder, ProductType.ProductModel dataBean,
                                     int position) {
            if (dataBean != null) {
                binding.setBean(dataBean);
                // if ("EPC".equalsIgnoreCase(dataBean.modelTypeId)) {
                //     binding.ivIcon.setImageResource(R.mipmap.ic_device_chief_machine);
                // } else if ("ZKQD".equalsIgnoreCase(dataBean.modelTypeId)) {
                //     binding.ivIcon.setImageResource(R.mipmap.ic_device_oven);
                // }
                BitmapUtil.loadUrl(dataBean.modelPicture, binding.ivIcon);
                binding.tvName.setText(dataBean.crmModelName);
                String type = "Wi-Fi智能";
                if (Constants.Type.BLENDER_Q8.equalsIgnoreCase(dataBean.modelId)
                        || Constants.Type.TYPE_ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(dataBean.modelId)) {
                    type = "NFC智能";
                } else if (Constants.Type.TYPE_VOLTAGE_POT.equalsIgnoreCase(dataBean.modelId)
                        || Constants.Type.TYPE_ELECTRIC_SAUCEPAN.equalsIgnoreCase(dataBean.modelId)
                        || Constants.Type.TYPE_VOLTAGE_POT_C100.equalsIgnoreCase(dataBean.modelId)
                        || Constants.Type.TYPE_BLENDER_66R.equalsIgnoreCase(dataBean.modelId)
                        || Constants.Type.TYPE_BLENDER_65S.equalsIgnoreCase(dataBean.modelId)
                        || Constants.Type.TYPE_BLENDER_905S.equalsIgnoreCase(dataBean.modelId)
                        || Constants.Type.TYPE_BLENDER_906R.equalsIgnoreCase(dataBean.modelId)) {
                    type = "NFC标签";
                }
                binding.tvTip.setText(type);

                if (positions.contains(position + 1)) {
                    binding.viewLine.setVisibility(View.GONE);
                } else {
                    binding.viewLine.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private class ViewBlankHolder extends BaseBindingHolder<ProductType.ProductModel,
            ItemNavigationBlankBinding> {

        ViewBlankHolder(ViewGroup context, int layoutId) {
            super(context, layoutId);
        }

        @Override
        protected void onBindingView(BaseBindingHolder holder, ProductType.ProductModel dataBean,
                                     int position) {
            if (dataBean != null) {
                blankView = binding.flBlank;
                binding.flBlank.setVisibility(View.VISIBLE);
            }
        }

    }
}
